package com.softserve;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.*;

import java.util.ArrayList;

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {

    // field of information about voyage
    private TextView info;
    //search field
    private EditText filterText = null;
    ArrayAdapter<String> adapter = null;

//    PersonsList personsList = new PersonsList();


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainlist);

        info = (TextView) findViewById(R.id.info);
        info.setText("Voyage 666, wait for 66 people");

        filterText = (EditText) findViewById(R.id.search_box);
        filterText.addTextChangedListener(filterTextWatcher);

        ArrayList<Person> p = new ArrayList<Person>();
        p.add(new Person("Name1", "Surname1", "Patronymic1", "ticketNumber1", "voyage1", "ticketClass1", "passport1"));
        p.add(new Person("Name2", "Surname2", "Patronymic2", "ticketNumber2", "voyage2", "ticketClass2", "passport2"));
        p.add(new Person("Name3", "Surname3", "Patronymic3", "ticketNumber3", "voyage3", "ticketClass3", "passport3"));
        PersonsList.setPersonList(p);

        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getStringArrayList()));
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(this);
    }

    private TextWatcher filterTextWatcher = new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s);
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        filterText.removeTextChangedListener(filterTextWatcher);
    }

    // get list of item to list
    private ArrayList getStringArrayList() {
        ArrayList<String> list = new ArrayList<String>();
        System.out.println("Checkpoint 2");
        for (Person p : PersonsList.getPersonList()) {
            list.add(new String(p.getName() + " " + p.getSurname() + " " + p.getPatronymic()));
        }
        return list;
    }

    // click to switch to another activity
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent i = new Intent(MainActivity.this, RegActivity.class);
        i.putExtra("selectionPosition", position);
        startActivity(i);
    }
}
